package com.soft.collateral.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.soft.collateral.entity.Contracts;
import com.soft.collateral.entity.Edger;
import com.soft.collateral.entity.UserRole;
import com.soft.collateral.exception.CollateralException;
import com.soft.collateral.mapper.ContractsMapper;
import com.soft.collateral.mapper.EdgerMapper;
import com.soft.collateral.service.EdgerService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.soft.collateral.vo.PageQueryVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;

/**
 * <p>
 * 押品台账表 服务实现类
 * </p>
 *
 * @author liubin
 * @since 2025-08-03
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class EdgerServiceImpl extends ServiceImpl<EdgerMapper, Edger> implements EdgerService {

    private final EdgerMapper edgerMapper;

    /**
     * 分页查询台账信息
     * @param vo
     * @return
     */
    @Transactional(readOnly = true)
    @Override
    public Page<Edger> page(PageQueryVO vo) {

        if(ObjectUtils.isEmpty(vo)){
            return null;
        }

        // 1.封装分页对象
        Page<Edger> page = Page.of(vo.getCurrentPage(), vo.getPageSize());
        LambdaQueryWrapper<Edger> wrapper = new LambdaQueryWrapper<>();

        // 2.按台账编号和更新时间查询
        wrapper.like(StringUtils.hasLength(vo.getQueryString()), Edger::getEdgerNumber, vo.getQueryString())
                .or().like(StringUtils.hasLength(vo.getQueryString()), Edger::getUpdateTime, vo.getQueryString());

        return edgerMapper.selectPage(page, wrapper);
    }

    /**
     * 新增台账
     * @param edger
     * @return
     */
    @Transactional
    @Override
    public boolean saveEdger(Edger edger) {
        // 检查押品是否已有台账
        LambdaQueryWrapper<Edger> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Edger::getCollateralId, edger.getCollateralId());
        Long count = edgerMapper.selectCount(wrapper);
        if(count > 0) {
            throw new CollateralException("此押品已有台账！");
        }

        // 设置台账编号和更新时间
        edger.setEdgerNumber("TZ-" + System.currentTimeMillis() / 1000);
        edger.setUpdateTime(LocalDate.now());

        return edgerMapper.insert(edger) > 0;
    }

    /**
     * 根据押品id查询台账
     * @param collateralId
     * @return
     */
    @Transactional(readOnly = true)
    @Override
    public Edger findByCollateralId(Integer collateralId) {

        Edger edger = edgerMapper.findByCollateralId(collateralId);
        return edger;

    }


}
